local zuilun = fk.CreateSkill {

  name = "joy__zuilun",

  tags = {  },

}



zuilun:addEffect(fk.EventPhaseStart, {
  name = "joy__zuilun",
  anim_type = "control",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and target:hasSkill(zuilun.name) and player.phase == Player.Finish
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local n = 0
    local events = player.room.logic:getEventsOfScope(GameEvent.ChangeHp, 1, function(e)
      local damage = e.data[5]
      return damage and player == damage.from
    end, Player.HistoryTurn)
    if #events > 0 then
      n = n + 1
    end
    events = room.logic:getEventsOfScope(GameEvent.MoveCards, 1, function(e)
      for _, move in ipairs(e.data) do
        if move.from==player and move.moveReason == fk.ReasonDiscard and table.find(move.moveInfo, function (info)
          return info.fromArea == Card.PlayerHand or info.fromArea == Card.PlayerEquip
        end) then
          return true
        end
      end
    end, Player.HistoryTurn)
    if #events == 0 then
      n = n + 1
    end
    if table.every(room.alive_players, function(p) return p:getHandcardNum() >= player:getHandcardNum() end) then
      n = n + 1
    end
    local cards = room:getNCards(4)
    local result = room:askForGuanxing(player, cards, {4 - n, 4 - n}, {n, n}, zuilun.name, true, {"zuilun_top", "zuilun_get"})
    if #result.top > 0 then
      for i = #result.top, 1, -1 do
        table.insert(room.draw_pile, 1, result.top[i])
      end
      room:sendLog{
        type = "#GuanxingResult",
        from = player.id,
        arg = #result.top,
        arg2 = #result.bottom,
      }
    end
    if #result.bottom > 0 then
      room:moveCardTo(result.bottom, Player.Hand, player, fk.ReasonJustMove, zuilun.name, "", false, player.id)
    end
    if n == 0 and not player.dead then
      local targets = table.map(room:getOtherPlayers(player), Util.IdMapper)
      local to = room:askForChoosePlayers(player, targets, 1, 1, "#zuilun-choose", zuilun.name, false)
      if #to > 0 then
        to = room:getPlayerById(to[1])
      else
        to = room:getPlayerById(table.random(targets))
      end
      room:loseHp(player, 1, zuilun.name)
      room:loseHp(to, 1, zuilun.name)
    end
  end,
})

return zuilun